package com.kevin.Code.String;

/**
 * @author Vinlee Xiao
 * @Classname BackspaceStringCompare
 * @Description Leetcode 844. 比较含退格的字符串 简单题
 * @Date 2022/1/21 17:06
 * @Version 1.0
 */
public class BackspaceStringCompare {
    /**
     * 字符串 技巧型题目
     *
     * @param s
     * @param t
     * @return
     */
    public boolean backspaceCompare(String s, String t) {

        int sLength = s.length() - 1;
        int tLength = t.length() - 1;

        //记录该跳过当前#号前的几个字符串
        int skipNum1 = 0;
        int skipNum2 = 0;

        while (sLength >= 0 || tLength >= 0) {

            //对s字符串进行判断
            while (sLength >= 0) {
                if (s.charAt(sLength) == '#') {
                    skipNum1++;
                } else if (s.charAt(sLength) != '#' && skipNum1 > 0) {
                    skipNum1--;

                } else {
                    break;
                }
                sLength--;
            }

            while (tLength >= 0) {
                if (t.charAt(tLength) == '#') {
                    skipNum2++;
                } else if (t.charAt(tLength) != '#' && skipNum2 > 0) {
                    skipNum2--;
                } else {
                    break;
                }
                tLength--;
            }

            if (sLength >= 0 && tLength >= 0) {
                if (s.charAt(sLength) != t.charAt(tLength)) {
                    return false;
                }
                //特殊情况 一个已经
            } else {
                //当其中有的坐标已经出现小于 0零时 而另外一个字符串还没有遍历完
                if (sLength >= 0 || tLength >= 0) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * @param s
     * @param t
     * @return
     */
    public boolean backspaceCompare1(String s, String t) {
        String s1 = getCorrectString(s);
        String s2 = getCorrectString(t);

        return s1.equals(s2);
    }

    /**
     * @param str
     * @return
     */
    private String getCorrectString(String str) {

        int index = str.length() - 1;
        int skipNum = 0;
        StringBuilder builder = new StringBuilder();
        while (index >= 0) {
            if (str.charAt(index) == '#') {
                skipNum++;
            } else if (str.charAt(index) != '#' && skipNum > 0) {
                skipNum--;
            } else {
                builder.append(str.charAt(index));
            }
            index--;
        }
        return builder.toString();
    }
}
